﻿using _9jCardRegisterCollection.Models;
using AntdUI;
using CardRegisterCollection.BLL;
using CardRegisterCollection.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Message = AntdUI.Message;
using Role = CardRegisterCollection.BLL.Role;
using UserRole = CardRegisterCollection.BLL.UserRole;

namespace _9jCardRegisterCollection.Views
{
    public partial class RoleManagementPage : UserControl
    {
        private AntdUI.Window window;
        private Role rolesBLL;
        private readonly Role _roleBll = new Role();
        private readonly CardRegisterCollection.BLL.Role roleBll = new CardRegisterCollection.BLL.Role();
        private UserRole UserRole;
        private readonly UserRole _userroleBll = new UserRole();
        private readonly CardRegisterCollection.BLL.UserRole userroleBll = new CardRegisterCollection.BLL.UserRole();
        AntList<RoleExpand> dataList;

        public RoleManagementPage(AntdUI.Window _window)
        {
            window = _window;
            InitializeComponent();


            //初始化表格列头
            InitTableColumns();

            InitData();
        }

        private void InitData()
        {
            var roleList = new List<RoleExpand>();

            var ds = _roleBll.GetListReturnDataset("");
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    roleList.Add(new RoleExpand
                    {
                        ID = row["ID"]?.ToString(),
                        name = row["name"]?.ToString(),
                        description = row["description"]?.ToString(),
                        CreatedBy = row.IsNull("CreatedBy") ? string.Empty : row["CreatedBy"].ToString(),
                        CreatedAt = row.IsNull("CreatedAt") ? (DateTime?)null : Convert.ToDateTime(row["CreatedAt"]),
                        DeleteFlag = Convert.ToBoolean(row["DeleteFlag"]),
                        LastUpdatedBy = row.IsNull("LastUpdatedBy") ? string.Empty : row["LastUpdatedBy"].ToString(),
                        LastUpdatedAt = row.IsNull("LastUpdatedAt") ? (DateTime?)null : Convert.ToDateTime(row["LastUpdatedAt"]),
                    });
                }
            }

            dataList = new AntList<RoleExpand>(roleList);
            tabRoles.Binding(dataList);
        }

        private void InitTableColumns()
        {
            tabRoles.Columns = new ColumnCollection() {
                new ColumnCheck("Selected"){Fixed = true},
                new Column("name", "角色名称", ColumnAlign.Center),
                new Column("description", "角色描述", ColumnAlign.Center),
                new Column("CreatedBy", "创建人", ColumnAlign.Center),
                new Column("CellLinks", "操作", ColumnAlign.Center)
                {
                    Fixed = true,//冻结列
                },

            };
        }

        private void butCreate_Click(object sender, EventArgs e)
        {
            var modelRole = new CardRegisterCollection.Model.Role()
            {
                ID = Guid.NewGuid().ToString(),
                CreatedAt = DateTime.Now,
                CreatedBy = CurrentLoginInfo.UserInfo.UserName
            };

            var form = new RoleAdd(window, modelRole) { };
            Modal.open(new AntdUI.Modal.Config(window, "创建角色", form, TType.None)
            {
                BtnHeight = 0,
            }); ;
            if (form.Submit)
            {
                _roleBll.Add(modelRole);
                InitData();
            }
        }

        private void tabRoles_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            var data = (RoleExpand)e.Record;
            if (data == null) return;

            var id = e.Btn.Id;
            switch (id)
            {
                case "Authorize":
                    {
                        var form = new RoleEdit(window,data.ID) { Size = new Size(500, 300) };
                        AntdUI.Drawer.open(new AntdUI.Drawer.Config(window, form)
                        {
                            OnLoad = () =>
                            {
                                AntdUI.Message.info(window, "进入授权", autoClose: 1);
                            },
                            OnClose = () =>
                            {
                                AntdUI.Message.info(window, "结束授权", autoClose: 1);
                            }
                        });
                    }
                    break;
                case "Edit":
                    {
                        var form = new RoleAdd(window, data);
                        Modal.open(new AntdUI.Modal.Config(window, "修改", form, TType.None)
                        {
                            BtnHeight = 0,
                        }); ;
                        if (form.Submit)
                        {
                            _roleBll.Update(data);
                            InitData();
                        }
                    }
                    break;
                case "Del":
                    {
                        DelById(data);
                    }
                    break;
            }
        }

        private void DelById(RoleExpand role)
        {
            var userExistRlt = userroleBll.ColumnValueExists("RoleID",role.ID);
            if (userExistRlt)
            {
                Message.warn(window, "存在用户绑定当前角色，无法删除");
                return;
            }

            _roleBll.Delete(role.ID);
            InitData();
        }

        private void butSearch_Click(object sender, EventArgs e)
        {
            var roleList = new List<RoleExpand>();
            DataSet ds = new DataSet();
            string strWhere = string.Empty;
            if (txtKeyword.Text.Trim().Length > 0)
            {
                strWhere += " name like '%" + txtKeyword.Text.Trim().ToString() + "%' ";
            }
            ds = _roleBll.GetListReturnDataset(strWhere);

            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    roleList.Add(new RoleExpand
                    {
                        ID = row["ID"]?.ToString(),
                        name = row["name"]?.ToString(),
                        description = row["description"]?.ToString(),
                        CreatedBy = row.IsNull("CreatedBy") ? string.Empty : row["CreatedBy"].ToString(),
                        CreatedAt = row.IsNull("CreatedAt") ? (DateTime?)null : Convert.ToDateTime(row["CreatedAt"]),
                        DeleteFlag = Convert.ToBoolean(row["DeleteFlag"]),
                        LastUpdatedBy = row.IsNull("LastUpdatedBy") ? string.Empty : row["LastUpdatedBy"].ToString(),
                        LastUpdatedAt = row.IsNull("LastUpdatedAt") ? (DateTime?)null : Convert.ToDateTime(row["LastUpdatedAt"]),
                    });
                }
            }

            dataList = new AntList<RoleExpand>(roleList);
            tabRoles.Binding(dataList);
        }
    }
}
